package com.kgc.sportscircle.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.kgc.sportscircle.pojo.Mallcart;
import com.kgc.sportscircle.pojo.Sportsuser;
import com.kgc.sportscircle.redis.LoginPrefix;
import com.kgc.sportscircle.redis.RedisService;
import com.kgc.sportscircle.service.MallcartService;
import com.kgc.sportscircle.utils.GetCookie;
import com.kgc.sportscircle.utils.ResultUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/cart")
public class MallcartController {
    @Reference(version = "1.11")
    private MallcartService mallcartService;
    @Resource
    RedisService redisService;

    @RequestMapping("/add")
    public Map addCart(String sku, int num, HttpServletRequest request){

        /**  获取用户*/
        String token = GetCookie.getSportsUserofCookie(request);
        Sportsuser sportsuser = redisService.get(LoginPrefix.getLoginList,token, Sportsuser.class);
        String userId = sportsuser.getId().toString();
        int flag = mallcartService.addCart(userId,sku,num);
        if (flag<=0){
            return ResultUtil.resultMap(false,"加入购物车失败",null);
        }
        return ResultUtil.resultMap(true,"加入购物车成功",null);
    }
    @RequestMapping("/getCart")
    public List<Mallcart> getCartList(HttpServletRequest request){
        String token = GetCookie.getSportsUserofCookie(request);
        Sportsuser sportsuser = redisService.get(LoginPrefix.getLoginList,token,Sportsuser.class);
        List<Mallcart> mallcarts = mallcartService.getCartList(sportsuser.getId().toString());
        return  mallcarts;
    }
    @RequestMapping("/updateCart")
    public Map updateCartNum(String sku,int num,HttpServletRequest request){
        String token = GetCookie.getSportsUserofCookie(request);
        Sportsuser sportsuser = redisService.get(LoginPrefix.getLoginList,token,Sportsuser.class);
        int flag = mallcartService.updateCartNum(sportsuser.getId().toString(),sku,num);

        if (flag<=0){
            return ResultUtil.resultMap(false,"更新失败",null);
        }else{
            return ResultUtil.resultMap(true,"更新成功",null);
        }
    }

}
